package hongcaosp.app.android.user.settings.safety.bind;

import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import hongcaosp.app.android.R;
import hongcaosp.app.android.login.UserToken;
import hongcaosp.app.android.user.settings.safety.bind.iview.BindPhoneIView;
import hongcaosp.app.android.user.settings.safety.bind.presenter.BindPhonePresenter;
import xlj.lib.android.base.component.BaseFragment;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.TaskPool;

public class BindPhoneFragment extends BaseFragment implements BindPhoneIView {

    private TextView tv_code;
    private EditText et_phone,et_code;

    private BindPhonePresenter presenter;

    private int time = 60;

    @Override
    public void initView() {
        presenter = new BindPhonePresenter(this);
        tv_code = findViewById(R.id.tv_code);
        et_phone = findViewById(R.id.et_phone);
        et_code = findViewById(R.id.et_code);

        findViewById(R.id.tv_code).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.sendCode(et_phone.getText().toString().trim());
            }
        });
        findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.bind(et_phone.getText().toString().trim(),et_code.getText().toString().trim());
            }
        });
    }

    @Override
    public int getLayoutRes() {
        return R.layout.fragment_bind_phone;
    }

    @Override
    public void sendCodeOver() {
        if (time <= 0) {
            time = 60;
            tv_code.setText("重新发送");
            tv_code.setEnabled(true);
            return;
        }
        TaskPool.myPool().postTaskOnMainDelay(new Runnable() {
            @Override
            public void run() {
                time --;
                tv_code.setText("重新发送(" + time +  ")");
                tv_code.setEnabled(false);
                sendCodeOver();
            }
        },1000);
    }

    @Override
    public void bindOver() {
        ToastManager.getInstance().showToast("绑定成功");
        UserToken.getDefault().getUser().setMobile(et_phone.getText().toString().trim());
        UserToken.getDefault().save();

        getActivity().finish();
    }
}
